import client from "../../utils/pool.mjs"
import { jsonResponse, httpCode } from "@/utils/index.mjs";
import { generateToken } from '@/service/auth.mjs';
import { validateVerificationCode } from '@/service/VerificationCode.mjs';

export async function POST(request) {

    // 从body中获取phone和pwd
    const formData = await request.json()
    const phone = formData.phone
    const scene = formData.scene
    const code = formData.code
    // 校验phone是否是合法手机号码
    if (!/^1[3456789]\d{9}$/.test(phone)) {
        return jsonResponse(httpCode.BUSINESS_ERROR, {
            message: '手机号码格式错误'
        })
    }
    // 从user库里面查询phone是否存在，存在的话再对比密码；使用ORM方法
    const user = await client.user.findFirst({
        where: {
            phone: phone.toString()
        }
    })
    try {
        const res = await validateVerificationCode(phone, scene, code)
        if (res) {
            return jsonResponse(200, {
                token: generateToken({ user_id: user.id })
            })
        }
    } catch (e) {
        console.log(e)
        jsonResponse(httpCode.BUSINESS_ERROR, { message: '手机或验证码错误' })
    }

    return jsonResponse(httpCode.BUSINESS_ERROR, { message: '手机或验证码错误' })
}
